package com.qk.common.util;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectRequest;
import com.qk.common.config.AliYunOSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class AliYunOSSOperators {

    @Autowired
    private AliYunOSSProperties aliYunOSSProperties;

    public String upload(byte[] content, String objectName) throws Exception {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliYunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliYunOSSProperties.getRegion())
                    .build();

            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    aliYunOSSProperties.getBucketName(),
                    objectName,
                    new ByteArrayInputStream(content)
            );
            ossClient.putObject(putObjectRequest);

            return "https://" + aliYunOSSProperties.getBucketName() + "." +
                    aliYunOSSProperties.getEndpoint().substring(8) + "/" + objectName;
        } catch (Exception e) {
            log.error("Caught an OSSException: " + e.getMessage());
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 获取 OSS 桶中所有文件 key 列表
     */
    public List<String> listAllFiles() {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliYunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliYunOSSProperties.getRegion())
                    .build();

            List<String> keys = new ArrayList<>();
            String nextMarker = null;

            while (true) {
                ObjectListing objectListing = ossClient.listObjects(aliYunOSSProperties.getBucketName(), nextMarker);
                for (OSSObjectSummary summary : objectListing.getObjectSummaries()) {
                    keys.add(summary.getKey());
                }
                if (!objectListing.isTruncated()) {
                    break;
                }
                nextMarker = objectListing.getNextMarker();
            }

            return keys;
        } catch (Exception e) {
            log.error("Failed to list files from OSS: {}", e.getMessage());
            throw new RuntimeException("OSS 文件列表获取失败", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 删除 OSS 中指定 key 的文件
     */
    public void deleteFile(String key) {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliYunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliYunOSSProperties.getRegion())
                    .build();

            ossClient.deleteObject(aliYunOSSProperties.getBucketName(), key);
            log.info("成功删除 OSS 文件: {}", key);
        } catch (Exception e) {
            log.error("Failed to delete file from OSS: key={}, error={}", key, e.getMessage());
            throw new RuntimeException("OSS 文件删除失败", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
